package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	pb "grpc-demo/complex/proto"
	"log"
	"time"
)

var grpcClient pb.SimpleClient

func route(ctx context.Context, deadlines time.Duration) {
	// 设置超时时间3秒
	clientDeadline := time.Now().Add(time.Duration(deadlines * time.Second))
	ctx, cancel := context.WithDeadline(ctx, clientDeadline)
	defer cancel()

	// 创建发送结构体
	req := pb.SimpleRequest{Data: "june"}
	// 调用服务，即Route()方法
	res, err := grpcClient.Route(ctx, &req)
	if err != nil {
		// 获取错误状态
		statu, ok := status.FromError(err)
		if ok {
			// 判断是否为调用超时
			if statu.Code() == codes.DeadlineExceeded {
				log.Fatalln("Route timeout!")
			}
		}
		log.Fatalf("Call Route err: %V", err)
	}
	fmt.Println(res)
}

func main() {
	// 连接服务器
	conn, err := grpc.Dial(":8000", grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	// 建立grpc连接
	grpcClient = pb.NewSimpleClient(conn)

	route(context.Background(), 3)
}
